# -*- coding: utf-8 -*-
from django.conf import settings
from apps.amway.models import Producto
from xlrd import open_workbook
from datetime import date
import os, re, shutil, xlrd



def get_xls_content(username):
    cod_list = []
    cant_list = []
    general_list = []
    path = os.path.join(settings.FILE_UPLOAD_TEMP_DIR, username)
    file_name = os.listdir(path)[0]
    file_path = os.path.join(path, file_name)
    try:
        book = open_workbook(file_path, encoding_override='utf-8', formatting_info=True)
        for name in book.sheet_names():
            sheet = book.sheet_by_name(name)
            for row_index in range(sheet.nrows):
                for col_index in range(sheet.ncols):
                    if type(sheet.cell(row_index, col_index).value) is unicode:
                        if re.search('codigo', sheet.cell(row_index, col_index).value, re.IGNORECASE):
                            cod_row_index = row_index
                            cod_col_index = col_index
                            #print cod_row_index, '--', cod_col_index                
                        elif re.search('cantidad', sheet.cell(row_index, col_index).value, re.IGNORECASE):
                            cant_row_index = row_index
                            cant_col_index = col_index
                            #print cant_row_index, '--', cant_col_index
    
        for cod_row in range(cod_row_index+1, sheet.nrows):
            if type(sheet.cell_value(cod_row, cod_col_index))  is int or type(sheet.cell_value(cod_row, cod_col_index)) is float:
                cod_list.append(int(sheet.cell_value(cod_row, cod_col_index))) 
        
        for cant_row in range(cant_row_index+1, sheet.nrows):
            if type(sheet.cell_value(cant_row, cant_col_index)) is int or type(sheet.cell_value(cant_row, cant_col_index)) is float:
                cant_list.append(int(sheet.cell_value(cant_row, cant_col_index)))
    
        if len(cod_list) == len(cant_list):
            for i in  range(0, len(cod_list)):
                try:
                    producto = Producto.objects.get(pk=cod_list[i])
                    general_list.append([ producto.descripcion, cant_list[i] ])
                except Producto.DoesNotExist:
                    pass 
    except :
        pass
    #shutil.rmtree(path)
            
    return general_list



def delete_tmp_dir(username):
    path = os.path.join(settings.FILE_UPLOAD_TEMP_DIR, username)
    if os.path.exists(path) is True:
        shutil.rmtree(path)
    